package com.atguigu.aclservice.service.impl;

import com.atguigu.aclservice.entity.User;
import com.atguigu.aclservice.service.PermissionService;
import com.atguigu.aclservice.service.UserService;
import com.atguigu.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    //操作菜单服务层
    @Autowired
    private UserService userService;

    //操作权限服务层
    @Autowired
    private PermissionService permissionService;

    /*
        根据用户名查询数据库,然后返回Security中指定的对象
    */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据用户名查询数据库
        User user = this.userService.selectByUsername(userName);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在!");
        }
        //创建spring_security模块中的User对象
        com.atguigu.security.entity.User curUser = new com.atguigu.security.entity.User();
        //将service_acl模块中的User对象的值复制到spring_security模块的User对象中
        BeanUtils.copyProperties(user,curUser);

        //根据用户查询用户权限列表
        List<String> permissionValueList = this.permissionService.selectPermissionValueByUserId(user.getId());

        //创建实现UserDetails接口的那个SecurityUser
        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUserInfo(curUser);
        securityUser.setPermissionValueList(permissionValueList);
        return securityUser;
    }
}
